import { NextApiRequest, NextApiResponse } from 'next'
import {withIronSessionApiRoute} from 'iron-session/next'
import md5 from 'md5' //加密
import { encode } from 'js-base64'
import { format } from 'date-fns'
import request from 'service/fetch'
import {ironOptions} from 'config/index'
import { ISession} from 'pages/api/index'

// 保存验证码到session
export default withIronSessionApiRoute(sendVerifyCode,ironOptions)

 async function sendVerifyCode(req:NextApiRequest, res:NextApiResponse) {
  // session
  const session:ISession = req.session
  const { to = '', templateId = '1'} = req.body
    // 容联云平台个人id及token、appid 
  const AppId = '2c94811c8cd4da0a018f0ed2724d6ee0'
  const AccountId = '2c94811c8cd4da0a018f0ed270cd6ed9'
  const AuthToken = '53b008fc5a3a4e1db57bc675070b3c84'
  // 时间戳插件 date-fns
  const NowDate = format(new Date(),'yyyyMMddHHmmss')
  // 请求数据
  const SigParameter = md5(`${AccountId}${AuthToken}${NowDate}`)
  // 请求头部
  const Authorization = encode(`${AccountId}:${NowDate}`)
  // 短信平台请求接口
  const url = `https://app.cloopen.com:8883/2013-12-26/Accounts/${AccountId}/SMS/TemplateSMS?sig=${SigParameter}`
  // 四位随机数
  const verifyCode = Math.floor(Math.random() * (9000 - 1000) + 1000)
  // 过期时间
  const expireMinute = '5'

  // 请求数据
  const response = await request.post(url,{
    to,
    templateId,
    appId:AppId,
    datas:[verifyCode,expireMinute]
  },{
    headers:{
      Authorization
    }
  })
  const {statusCode,statusMsg,TemplateSMS} = response as any;
  // 保存验证码到session
  if(statusCode === '000000'){
    session.verifyCode = verifyCode
    await session.save()
    res.status(200).json({
      code: 0,
      msg: statusMsg,
      data:{
        TemplateSMS
      }
    })
  }else{
    res.status(200).json({
      code:statusCode,
      msg: statusMsg
    })
  }

}